import os
import re
import pickle
import webbrowser
import requests
import json

# 定义cookie文件路径
COOKIE_FILE = "qq_music_cookies.pkl"

def load_cookies():
    """
    加载保存的QQ音乐cookie
    :return: 保存的cookie或None
    """
    try:
        if os.path.exists(COOKIE_FILE):
            with open(COOKIE_FILE, 'rb') as f:
                cookies = pickle.load(f)
                print("成功加载QQ音乐登录信息")
                return cookies
        else:
            print("未找到保存的登录信息")
            return None
    except Exception as e:
        print(f"加载cookie失败: {e}")
        return None

def save_cookies(cookies):
    """
    保存QQ音乐cookie
    :param cookies: 要保存的cookie
    :return: 是否保存成功
    """
    try:
        with open(COOKIE_FILE, 'wb') as f:
            pickle.dump(cookies, f)
        print("登录信息已保存")
        return True
    except Exception as e:
        print(f"保存cookie失败: {e}")
        return False

def open_login_page():
    """
    打开QQ音乐登录页面
    """
    login_url = "https://y.qq.com/"
    print(f"打开QQ音乐登录页面: {login_url}")
    webbrowser.open(login_url)

def extract_cookies_from_curl(curl_command):
    """
    从cURL命令中提取cookie
    :param curl_command: cURL命令字符串
    :return: 提取的cookie字典或None
    """
    try:
        # 尝试多种格式的cookie提取
        # 1. 标准格式: -H "Cookie: name=value; name2=value2"
        cookie_match = re.search(r'-H\s+[\'"]Cookie:\s+(.*?)[\'"]', curl_command)
        
        # 2. 另一种格式: --cookie "name=value; name2=value2"
        if not cookie_match:
            cookie_match = re.search(r'--cookie\s+[\'"]?(.*?)[\'"]?\s', curl_command)
        
        # 3. 直接从header中提取: -H "name: value" 格式的所有cookie头
        if not cookie_match:
            # 查找所有可能的cookie头
            all_cookies = []
            for match in re.finditer(r'-H\s+[\'"]([^:]+):\s+([^\'"]*)[\'"]\s', curl_command):
                header_name = match.group(1).lower()
                if header_name == 'cookie':
                    all_cookies.append(match.group(2))
            
            if all_cookies:
                cookie_str = "; ".join(all_cookies)
                cookie_match = True  # 设置为True，但不使用re.search的结果
            
        # 如果找到了cookie
        if cookie_match:
            if isinstance(cookie_match, bool):
                # 使用前面提取的cookie_str
                pass
            else:
                cookie_str = cookie_match.group(1)
            
            # 将cookie字符串转换为字典
            cookies = {}
            for item in cookie_str.split('; '):
                if '=' in item:
                    name, value = item.split('=', 1)
                    cookies[name] = value
            
            if cookies:
                print("成功提取登录信息")
                return cookies
        
        # 如果上面的方法都失败了，尝试直接从整个命令中提取所有cookie格式的字符串
        cookie_pattern = re.compile(r'([a-zA-Z0-9_\-\.]+)=([^;]+)')
        all_cookies = cookie_pattern.findall(curl_command)
        if all_cookies:
            cookies = {name: value for name, value in all_cookies}
            if cookies:
                print("成功从命令中提取登录信息")
                return cookies
        
        print("无法从cURL命令中提取cookie，请确保复制了完整的命令")
        return None
    except Exception as e:
        print(f"处理cURL命令失败: {e}")
        return None

def check_login_status(cookies):
    """
    检查登录状态是否有效
    :param cookies: QQ音乐cookie
    :return: 登录是否有效
    """
    if not cookies:
        return False
    
    try:
        # 构建请求头
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Referer': 'https://y.qq.com/',
            'Cookie': '; '.join([f"{k}={v}" for k, v in cookies.items()])
        }
        
        # 请求用户信息接口
        url = "https://c.y.qq.com/rsc/fcgi-bin/fcg_get_profile_homepage.fcg"
        params = {
            'format': 'json',
            'inCharset': 'utf-8',
            'outCharset': 'utf-8',
            'platform': 'yqq',
            'cid': '205360838',
            'ct': '20',
            'userid': '0',
            'reqfrom': '1',
            'reqtype': '0'
        }
        
        response = requests.get(url, headers=headers, params=params, timeout=10)
        response.raise_for_status()
        
        data = response.json()
        
        # 检查是否包含用户信息
        if 'data' in data and 'creator' in data['data'] and data['data']['creator'].get('nick'):
            return True
        
        return False
    except Exception as e:
        print(f"检查登录状态失败: {e}")
        return False

def get_user_info(cookies):
    """
    获取用户信息
    :param cookies: QQ音乐cookie
    :return: 用户信息字典或None
    """
    if not cookies:
        return None
    
    try:
        # 构建请求头
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Referer': 'https://y.qq.com/',
            'Cookie': '; '.join([f"{k}={v}" for k, v in cookies.items()])
        }
        
        # 请求用户信息接口
        url = "https://c.y.qq.com/rsc/fcgi-bin/fcg_get_profile_homepage.fcg"
        params = {
            'format': 'json',
            'inCharset': 'utf-8',
            'outCharset': 'utf-8',
            'platform': 'yqq',
            'cid': '205360838',
            'ct': '20',
            'userid': '0',
            'reqfrom': '1',
            'reqtype': '0'
        }
        
        response = requests.get(url, headers=headers, params=params, timeout=10)
        response.raise_for_status()
        
        data = response.json()
        
        # 提取用户信息
        if 'data' in data and 'creator' in data['data']:
            creator = data['data']['creator']
            user_info = {
                'nickname': creator.get('nick', '未知用户'),
                'avatar': creator.get('headpic', ''),
                'is_vip': creator.get('isvip', 0) == 1
            }
            return user_info
        
        return None
    except Exception as e:
        print(f"获取用户信息失败: {e}")
        return None

def logout():
    """
    退出登录
    :return: 是否成功退出
    """
    try:
        if os.path.exists(COOKIE_FILE):
            os.remove(COOKIE_FILE)
            print("已清除登录信息")
            return True
        return False
    except Exception as e:
        print(f"退出登录失败: {e}")
        return False